<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template v-if="tname == '国家分析'" slot="title">论文发表机构所在国家</template>
      <template v-else slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="0"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
        <div class="right-tools">
          <span
            @click="handleShowContrastive"
            v-if="tname == '申请人趋势分析' || tname == '发明人趋势分析'"
            >对比分析</span
          >
        </div>
      </template>
      <template slot="chart">
        <ChartI
          v-if="datatype !== -1"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
          @contrastiveData="getContrastiveData"
        /> 
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
        <i class="icon el-icon-full-screen" @click="handleFullScreen">&nbsp;全屏</i>
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p style="flex:none;width: 30px;"></p>
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p style="flex:none;width: 30px;"><el-checkbox v-model="checkList[index]" :key="index" @change="handleChangeCheck">&nbsp;</el-checkbox></p>
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item" :key="j">
            <span v-if="!tableData.inputRefs[index][j]" @click="handleClick(ite)">{{ ite }}</span>
            <span v-else>
              <el-input v-model="tableData._content[index][j]" placeholder="" size="mini" :style="{'min-width': tableData._content[index][j].length >= 10 ? '230px' : '100px'}"></el-input>
            </span>
            <span class="tools-box">
              <!-- 修改 -->
              <i v-if="!tableData.inputRefs[index][j]" class="tools-btn el-icon-edit" @click="handleShowInp(index, j)"></i>
              <!-- 保存 -->
              <i v-if="tableData.inputRefs[index][j]" class="tools-btn el-icon-check" @click="handleUpdateIte(index, j)"></i>
              <!-- 取消 -->
              <i v-if="tableData.inputRefs[index][j]" class="tools-btn el-icon-close" @click="handleShowInp(index, j)"></i>
            </span>
          </p>
        </li>
      </ul>
    </div>
    <!-- 对比分析 -->
    <Contrastive ref="contrastive" />
  </div>
</template>
<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartI from "../charts/ChartI";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry,
  isShowContrastBtn,
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import Contrastive from "../Contrastive";
import ChooseScreen from "./chooseScreen.vue";
import { handlesShowtopsize } from "@/utils/utils";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object,
    },
    dcData: {
      type: Object,
    },
  },
  components: {
    CSlot,
    ChartI,
    Contrastive,
    ChooseScreen,
  },
  data() {
    return {
      searchTxt: "",
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      selectATit: "", // 筛选条件B，动态
      timeType: "isd", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      chartData: [],
      _chartData: [], // 记录原始chartData
      chartType: "line",
      dom: {},
      domRef: null, // 记录图表dom对象，用于全屏
      tableData: {
        tit: ["索引","国家", "论文量", ],
        content: [],
        _content: [], // 存储修改content值
        inputRefs: [], // 记录修改展示的input的值
      },
      checkList: [], // 多选框勾选数据
      yearArr: [],
      contrastiveData: [], // 对比分析的数据
      emptyText: "数据加载中...",
      dbid: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "",
      msq: "",
    };
  },
  computed: {
    ...mapState(["searchWord"]),
  },
  watch: {
    // chartTempl() {
    //   this.init();
    // },
    dcData() {
      this.init();
    },
  },
  mounted() {
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this._chartData = []
      this.tableData.content = [];
      this.tableData._content = [];
      this.tableData.inputRefs = []
      this.checkList = []
      this.loading = true;
      this.tname = this.chartTempl.tname;
      if(this.tname == "国家分析"){
        this.$set(this.tableData.tit, 1, "国家");
      }
      if(this.tname == "机构分析"){
        this.$set(this.tableData.tit, 1, "机构");
      }
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      if (this.dcData && this.dcData.chartData) {
        if (handlesShowtopsize(this.tname)) {
          this.dcData.chartData = this.dcData.chartData.slice(0,10) //特定情况下 默认展示前Params.size
        }
        //默认取前10
        let data = JSON.parse(JSON.stringify(this.dcData.chartData));
        this.loading = false;
        data.forEach((v) => {
          v.key = transCNCountry(v.key);
        });
        refactor({
          type: this.dcData.datatype, // 根据后台返回的datatype，判断数据解析格式
          data,
          callback: (refactor) => {
            this.chartData = [refactor.seriesData] || [];
            this._chartData = [refactor.seriesData] || [];
            refactor.seriesData.xData.map((it, i) => {
              this.tableData.content.push([ it, refactor.seriesData.paperData[i]]);
              this.tableData._content.push([ it, refactor.seriesData.paperData[i]]);
              this.checkList.push(true)
              // 记录inputRefs
              let arr = this.tableData._content[0]
              let boo = []
              arr.map((v, k) => {
                boo.push(false)
              })
              this.tableData.inputRefs.push(boo)
            });
          },
        });
      }
      this.handleParams();
    },
    // 修改表格文字内容
    handleUpdateIte(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请勾选后再进行修改",
        });
        return
      }
      this.$set(this.tableData.content[index], j, this.tableData._content[index][j])
      this.handleShowInp(index, j)
      // 重新设置chartData数据
      let chartData = JSON.parse(JSON.stringify(this.chartData))
      if (j == 0) {
        chartData[0]["xData"][index] = this.tableData.content[index][j]
      } else if (j == 1) {
        chartData[0]["paperData"][index] = this.tableData.content[index][j]
      }
      this.chartData = chartData
    },
    // 显隐修改表格文字input框
    handleShowInp(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请选勾选后再进行修改",
        });
        return
      }
      if (this.tableData.inputRefs[index][j] === true) {
        this.$set(this.tableData.inputRefs[index], j, false)
      } else {
        this.$set(this.tableData.inputRefs[index], j, true)
      }
    },
    // 勾选
    handleChangeCheck() {
      let chartData = JSON.parse(JSON.stringify(this.chartData))
      this.checkList.forEach((v, index) => {
        if (v === true) {
          chartData[0]["avgData"][index] = this._chartData[0]["avgData"][index]
          chartData[0]["expertData"][index] = this._chartData[0]["expertData"][index]
          chartData[0]["xData"][index] = this.tableData._content[index][0]
          chartData[0]["paperData"][index] = this.tableData._content[index][1]
        } else {
          chartData[0]["avgData"][index] = null
          chartData[0]["expertData"][index] = null
          chartData[0]["xData"][index] = null
          chartData[0]["paperData"][index] = null
        }
      })
      chartData[0]["avgData"] = chartData[0]["avgData"].filter(v => v !== null)
      chartData[0]["expertData"] = chartData[0]["expertData"].filter(v => v !== null)
      chartData[0]["xData"] = chartData[0]["xData"].filter(v => v !== null)
      chartData[0]["paperData"] = chartData[0]["paperData"].filter(v => v !== null)
      this.chartData = chartData
    },
    // 拼装sq 给对比分析使用
    handleParams() {
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=2012${this.datefieldformatTxt} AND ${this.timeType}<=2022${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq;
      }
      this.msq = sq;
    },
    getChartData(Params) {
      if (this.cancel !== null) {
        this.cancel();
      }
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq;
      }
      this.msq = sq;
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this._chartData = [];
      this.tableData = {
        tit: [],
        content: [],
        _content: [],
        inputRefs: []
      };
      this.checkList = []
      //触发search接口
      let params = {
        aggs: this.chartTempl.tdata.param.aggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 0,
        rSearch: "",
        smartSearch: "",
      };
      params.aggs[0]["size"] = Params.size;
      params.aggs[0]["parameters"]["size"] = Params.size;
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let ths = this;
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        }),
      })
        .then((res) => {
          let data = JSON.parse(JSON.stringify(res.data.chartData));
          this.$store.commit("setTotalTxt", res.data.total);
          if (handlesShowtopsize(this.tname)) {
            data = data.slice(0,Params.size)//特定情况下 默认展示前Params.size
          }
          this.loading = false;
          data.forEach((v) => {
            v.key = transCNCountry(v.key);
          });
          refactor({
            type: this.dcData.datatype, // 根据后台返回的datatype，判断数据解析格式
            data,
            callback: (refactor) => {
              this.chartData = [refactor.seriesData] || [];
              this._chartData = [refactor.seriesData] || [];
              refactor.seriesData.xData.map((it, i) => {
                this.tableData.content.push([ it, refactor.seriesData.paperData[i]]);
                this.tableData._content.push([ it, refactor.seriesData.paperData[i]]);
                this.checkList.push(true)
                // 记录inputRefs
                let arr = this.tableData._content[0]
                let boo = []
                arr.map((v, k) => {
                  boo.push(false)
                })
                this.tableData.inputRefs.push(boo)
              });
            },
          });
        })
        .catch((err) => {
          // this.emptyText = "暂无数据";
          this.loading = false;
        });
    },
    getDomRef(dom) {
      this.domRef = dom
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 全屏
    handleFullScreen() {
      let element = this.domRef
      if (!element) {
        return
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 对比分析
    getContrastiveData(data) {
      this.contrastiveData = data;
    },
    handleShowContrastive() {
      if (this.contrastiveData.length <= 0) {
        this.$message.warning("请至少选择一项数据！");
        return;
      }
      this.$refs.contrastive.init(
        this.contrastiveData,
        this.chartTempl,
        this.dbid,
        this.msq
      );
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws =
        XLSX.utils.aoa_to_sheet(aoa); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    },
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  },
};
</script>

<style lang="scss"></style>
